import os.path
import re
import sys
import time

import polars as pl
import tkinter as tk
from tkinter import filedialog

def select_file(prompt_message):  # prompt_message 提示信息
    root = tk.Tk()
    root.withdraw()
    root.attributes('-topmost', True)  # 将窗口置顶
    return filedialog.askopenfilename(title=prompt_message, filetypes=[('Excel files', '*.xlsx')])

# 编译正则表达式
pattern_p = {
    36: re.compile(r'P(\w{8})'),
    40: re.compile(r'P(\w{8})'),
    44: re.compile(r'P(.{12})'),
    45: re.compile(r'P(\w{8})'),
    47: re.compile(r'P(.*?)1P'),
    48: re.compile(r'P(.*?)1P'),
    49: re.compile(r'P(.*?)1P'),
    50: re.compile(r'P(.*?)1P'),
    51: re.compile(r'P(.*?)1P'),
    52: re.compile(r'P(.*?)1P'),
    53: re.compile(r'P(.*?)1P'),
    54: re.compile(r'P(.*?)1P'),
    56: re.compile(r'P(.*?)1P'),
    57: re.compile(r'P(.*?)1P')
}

pattern_s = {
    36: re.compile(r'S(\w{12})'),
    40: re.compile(r'S(\w{12})'),
    44: re.compile(r'S(\w{12})'),
    45: re.compile(r'S(\w{16})'),
    47: re.compile(r'[^S]+$'),
    48: re.compile(r'[^S]+$'),
    49: re.compile(r'[^S]+$'),
    50: re.compile(r'[^S]+$'),
    51: re.compile(r'[^S]+$'),
    52: re.compile(r'[^S]+$'),
    53: re.compile(r'[^S]+$'),
    54: re.compile(r'[^S]+$'),
    56: re.compile(r'[^S]+$'),
    57: re.compile(r'[^S]+$')
}

def extract_code_and_barcode(qr_code):
    length = len(qr_code)
    code, barcode = "", ""

    # 获取预编译的正则表达式模式
    match_p = pattern_p.get(length)
    match_s = pattern_s.get(length)

    if match_p:
        match_p = match_p.search(qr_code)
        if match_p:
            code = match_p.group(1).strip()

    if match_s:
        match_s = match_s.search(qr_code)
        if match_s:
            if length in {47, 48, 49, 50, 51, 52, 53, 54, 56, 57}:
                index = match_s.group(0).find("4L")
                if index != -1:
                    barcode = match_s.group(0)[:index].strip()
            else:
                barcode = match_s.group(1).strip()

    return code, barcode

def read_excel():
    excel_file = select_file("选择要解析的二维码Excel文件")
    if not excel_file:
        print("未选择文件。")
        return
    # 开始计时
    start_time = time.time()

    # 使用 Polars 读取 Excel 文件
    df = pl.read_excel(excel_file, sheet_id=1, read_options={'use_columns': ['二维码条码']}, engine="calamine")

    # 使用 Polars 的向量化操作来处理数据
    df = df.with_columns([
        pl.col("二维码条码").map_elements(lambda x: extract_code_and_barcode(x)[0], return_dtype=pl.Utf8).alias("编码"),
        pl.col("二维码条码").map_elements(lambda x: extract_code_and_barcode(x)[1], return_dtype=pl.Utf8).alias("条码")
    ])
    current_dir = os.path.dirname(os.path.realpath(sys.argv[0]))  # 获取当前文件所在目录路径
    df.write_excel(os.path.join(current_dir,"output.xlsx"), worksheet="Sheet1")

    # 结束计时
    end_time = time.time()
    print(f"处理完成，耗时 {end_time - start_time:.2f} 秒。")



if __name__ == '__main__':
    try:
        read_excel()
    except Exception as e:
        print(f"发生错误: {e}")
        input("按回车键退出...")
        exit()
    print("处理完成。")
    input("按回车键退出...")
    exit()
